<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                <el-form-item label="管道ID" style="width: 300px;">
                    <el-input v-model="searchForm.pipeId" placeholder="管道ID"></el-input>
                </el-form-item>
                <el-form-item label="管道业务编号" style="width: 300px;">
                    <el-input v-model="searchForm.pipeCode" placeholder="管道业务编号"></el-input>
                </el-form-item>
                <el-form-item label="材质" style="width: 300px;">
                    <el-select v-model="searchForm.material" placeholder="材质">
                        <el-option v-for="item in dictData" :label="item.dictLabel" :value="item.dictValue"
                            :key="item.dictValue"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card class="mt-2">
            <!-- 操作按钮 -->
            <el-row :getter="20">
                <el-col :span="12">
                    <div>
                        <el-button type="primary" @click="handleAdd" icon="Plus">新增</el-button>
                        <el-button type="danger" @click="handleBatchDelete" :disabled="!multipleSelection.length"
                            icon="Delete">批量删除</el-button>
                    </div>
                </el-col>
                <!-- <el-col :span="12" class="flex-end">
                    <right-toolbar :search="false" v-model:showSearch="showSearch" @queryTable="loadData"
                        :columns="columns"></right-toolbar>
                </el-col> -->
            </el-row>
            <!-- 数据表格 -->
            <div class="table-container mt-2">
                <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column prop="pipeId" label="管道ID" align="center"
                        v-if="columns[0].visible"></el-table-column>
                    <el-table-column prop="material" label="材质" align="center" v-if="columns[1].visible">
                        <template #default="{ row }">
                            <el-tag> {{dictData.find(item => item.dictValue == row.material)?.dictLabel}} </el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column prop="caliber" label="管道口径(mm)" align="center"
                        v-if="columns[2].visible"></el-table-column>
                    <el-table-column prop="length" label="管道长度(m)" align="center"
                        v-if="columns[3].visible"></el-table-column>
                    <el-table-column prop="burialDepth" label="管线埋深" align="center"
                        v-if="columns[4].visible"></el-table-column>
                    <el-table-column prop="installAddress" label="安装地址" align="center"
                        v-if="columns[5].visible"></el-table-column>
                    <el-table-column prop="linePosition" label="管理线路位置" align="center" v-if="columns[6].visible">
                        <template #default="{ row }">
                            <div>{{ row.linePosition.slice(0, 10) + '...' }}</div>
                        </template>
                    </el-table-column>
                    <!-- 新增管网图片列 -->
                    <el-table-column prop="fileId" label="管网图片" align="center" v-if="columns[7].visible">
                        <template #default="{ row }">
                            <el-image style="width: 30px; height: 30px" :src="getImageUrl(row.pipeImage)"
                                :preview-src-list="[getImageUrl(row.pipeImage)]" fit="cover" preview-teleported>
                                <template #error>
                                    <div class="image-slot">
                                        <el-icon>
                                            <Picture />
                                        </el-icon>
                                    </div>
                                </template>
                            </el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="installDate" label="安装日期" align="center" v-if="columns[8].visible">
                        <template #default="{ row }">
                            {{ row.installDate }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="runStatus" label="状态" align="center" v-if="columns[9].visible">
                        <template #default="{ row }">
                            <el-tag :type="row.runStatus == '0' ? 'success' : 'danger'">
                                {{ row.runStatus == '0' ? '正常' : '报警' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="pipeCode" label="管道业务编号" align="center"
                        v-if="columns[10].visible"></el-table-column>
                    <el-table-column label="操作" align="center" fixed="right" v-if="columns[11].visible">
                        <template #default="{ row }">
                            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                            <el-button size="small" type="danger" @click="handleDelete(row.pipeId)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" :close-on-click-modal="false">
            <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="管道业务编号" prop="pipeCode">
                            <el-input v-model="formData.pipeCode" placeholder="请输入管道业务编号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="材质" prop="material">
                            <el-select v-model="formData.material" placeholder="请选择材质">
                                <el-option v-for="item in dictData" :label="item.dictLabel" :value="item.dictValue"
                                    :key="item.dictValue"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="管道口径(mm)" prop="caliber">
                            <el-input v-model="formData.caliber" placeholder="请输入管道口径"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="管道长度(m)" prop="length">
                            <el-input v-model="formData.length" placeholder="请输入管道长度"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="安装地址" prop="installAddress">
                            <el-input v-model="formData.installAddress" placeholder="详细到门牌号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="安装日期" prop="installDate">
                            <el-date-picker v-model="formData.installDate" type="date" placeholder="选择日期"
                                value-format="YYYY-MM-DD" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="关联工厂ID" prop="plantId">
                            <el-input v-model="formData.plantId" placeholder="关联工厂ID"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="管理深度(m)" prop="burialDepth">
                            <el-input v-model="formData.burialDepth" placeholder="请输入管理深度"></el-input>
                        </el-form-item>
                    </el-col>
                   
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="状态" prop="runStatus">
                            <el-select v-model="formData.runStatus" placeholder="请选择状态">
                                <el-option label="正常" :value="0"></el-option>
                                <el-option label="报警" :value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="管道定位" label-width="80px">
                            <el-input v-model="formData.linePosition" placeholder="请输入管理深度"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 新增管网图片上传 -->
                <el-form-item label="管网图片" prop="pipeImage">
                    <UploadFile @success="handleUploadSuccess" :files="formData.pipeImage" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Picture } from '@element-plus/icons-vue'
import UploadFile from '@/components/UploadFile/index.vue'

import {
    getPipeList,
    getPipeDetail,
    addPipe,
    updatePipe,
    deletePipe,
    getDictData
} from '@/api/dispatch/detection/pipelineRetworkMonitoring'

const dictData = ref([]);
const showSearch = ref(true);
// 搜索表单
const searchForm = reactive({
    pipeId: '',
    pipeCode: '',
    material: '',
    status: ''
})

// 表格数据
const tableData = ref([])

// 列显隐信息
const columns = ref([
    { key: 0, label: `管道ID`, visible: true },
    { key: 1, label: `材质`, visible: true },
    { key: 2, label: `管道口径`, visible: true },
    { key: 3, label: `管道长度`, visible: true },
    { key: 4, label: `管线埋深`, visible: true },
    { key: 5, label: `安装地址`, visible: true },
    { key: 6, label: `管理线路位置`, visible: true },
    { key: 7, label: `管网图片`, visible: true },
    { key: 8, label: `安装日期`, visible: true },
    { key: 9, label: `运行状态`, visible: true },
    { key: 10, label: `管道业务编号`, visible: true },
    { key: 11, label: `操作`, visible: true },
])

// 分页数据
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增管道配置')
const formRef = ref(null)
const formData = reactive({
})

// 表单验证规则
const rules = reactive({
    pipeCode: [{ required: true, message: '请输入管道业务编号', trigger: 'blur' }],
    material: [{ required: true, message: '请选择材质', trigger: 'change' }],
    caliber: [{ required: true, message: '请输入管道口径', trigger: 'blur' }],
    length: [{ required: true, message: '请输入管道长度', trigger: 'blur' }],
    installAddress: [{ required: true, message: '请输入安装地址', trigger: 'blur' }],
    installDate: [{ required: true, message: '请选择安装日期', trigger: 'change' }]
})

// 多选
const multipleSelection = ref([])
// 获取图片URL
const getImageUrl = (pipeImage) => {
    if (!pipeImage) return null;
    return import.meta.env.VITE_APP_IMAGE_URL + pipeImage;
}

// 上传成功
const handleUploadSuccess = (ids) => {
    formData.fileId = ids[0];
}

// 加载数据
const loadData = async () => {
    try {
        const params = {
            ...searchForm,
            pageNum: pagination.currentPage,
            pageSize: pagination.pageSize
        }
        const res = await getPipeList(params)
        tableData.value = res.rows
        pagination.total = res.total
    } catch (error) {
        console.error('加载数据失败:', error)
    }
}



// 其他方法保持不变...
// (handleSearch, resetSearch, handleSizeChange, handleCurrentChange等)

// 重置搜索
const resetSearch = () => {
    Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
    })
    handleSearch()
}
// 分页大小变化
const handleSizeChange = (val) => {
    pagination.pageSize = val
    loadData()
}
// 多选变化
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}
// 当前页变化
const handleCurrentChange = (val) => {
    pagination.currentPage = val
    loadData()
}

// 搜索
const handleSearch = () => {
    pagination.currentPage = 1
    loadData()
}
// 新增
const handleAdd = () => {
    dialogTitle.value = '新增管道配置'
    resetForm()
    dialogVisible.value = true

}

// 编辑
const handleEdit = async (row) => {
    dialogTitle.value = '编辑管道配置'
    try {
        const res = await getPipeDetail(row.pipeId)
        Object.assign(formData, res.data);
        dialogVisible.value = true
    } catch (error) {
        console.error('获取详情失败:', error)
        ElMessage.error('获取详情失败')
    }
}

// 重置表单
const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
    Object.keys(formData).forEach(key => {
        formData[key] = key === 'status' ? '0' : key === 'weight' ? 5 : ''
    })
}

// 提交表单
const submitForm = async () => {
    try {
        await formRef.value.validate()

        if (dialogTitle.value === '新增水表设备') {
            await addPipe(formData)
            ElMessage.success('新增成功')
        } else {
            await updatePipe(formData)
            ElMessage.success('更新成功')
        }

        dialogVisible.value = false
        loadData()
    } catch (error) {
        console.error('表单提交失败:', error)
        if (error !== 'validate') {
            ElMessage.error('操作失败')
        }
    }
}

getDictData({ dictType: 'guanwang_caizhi' }).then((response) => {
    dictData.value = response.data;
})

// 初始化加载数据
onMounted(() => {
    loadData()
})
</script>

<style scoped>
.search-container {
    margin-bottom: 20px;
}

.action-buttons {
    margin-bottom: 20px;
}

.table-container {
    margin-bottom: 20px;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
}

.image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;
}
</style>